package com.shiliao.app.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.shiliao.app.R;
import com.shiliao.app.ShiliaoApplication;
import com.shiliao.app.activity.Feedback.ui.DynamicFragment;
import com.shiliao.app.activity.index.presenter.MainPresenter;
import com.shiliao.app.activity.index.ui.IndexFragment;
import com.shiliao.app.activity.index.view.MainView;
import com.shiliao.app.activity.interlocution.ui.InterlocutionFragment;
import com.shiliao.app.activity.personal.ui.PersonalFragment;
import com.shiliao.app.event.MessageEvent;
import com.shiliao.app.manager.YMUserManager;
import com.shiliao.app.update.UpdateEntity;
import com.shiliao.app.update.YimeiFileDownloadDialog;
import com.shiliao.app.utils.FileNameManage;
import com.shiliao.app.utils.PermissionsChecker;
import com.shiliao.app.weight.NoScrollViewPager;
import com.shiliao.app.weight.TabView;
import com.yimei.framework.base.event.BaseMessageEvent;
import com.yimei.framework.base.ui.BaseActivity;
import com.yimei.framework.base.ui.BaseFragment;
import com.yimei.framework.util.DensityUtils;
import com.yimei.framework.util.LogUtil;
import com.yimei.framework.util.PreferenceHelper;
import com.yimei.framework.util.StatusBarCompat;
import com.yimei.framework.util.SystemUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by yinzhiqiang on 2017/9/6.
 */

public class MainActivity extends BaseActivity implements TabView.PageChangeListener, MainView {
    private static Context sContext = null;
    private long mInterval = 0; // 兩次返回鍵的间隔时间
    private final long mDiffTime = 2000; // 两次返回键小于2秒 则退出
    public static final int POSITION_INDEX = 0;//首页
    public static final int POSITION_INTERLOCUTION = 1;//问答
    public static final int POSITION_PERSONAL = 3;//个人中心
    public static final int POSITON_FEEDBACK = 2;//意见建议
    public static final String TO_LOGIN = "to_login";
    private boolean bShowNewMsg = false;


    @BindView(R.id.v_tab_title)
    TabView tabView;
    @BindView(R.id.v_viewpager)
    NoScrollViewPager mViewPager;

    @BindView(R.id.tv_bg)
    TextView tvBg;
    private ArrayList<BaseFragment> mFragments;
    private ArrayList<IPageChangedListener> mPageChangeLisenters = new ArrayList<>();
    protected static int mCurrentView = POSITION_INDEX;//当前页面
    private List<String> tabTitles;
    private List<Integer> tabImagesNor;
    private List<Integer> tabImagesSel;
    private YimeiFileDownloadDialog yimeiFileDownloadDialog;
    private MainPresenter mainPresenter;
    private SimpleDateFormat formatter;
    private NotificationManager notificationManager;
    private View personalCenter;
    private PopupWindow pomenuGuid;
    private boolean ishow = false;
    private String isShowGuide;

    public static int getCurrentView() {
        return mCurrentView;
    }

    public static void setCurrentView(int currentView) {
        mCurrentView = currentView;
    }

    public static Context getContext() {
        return sContext;
    }

    public interface IPageChangedListener {
        void onPageChanged(int position);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        //  LogUtil.e("yjl", "mainactivity onNewIntent");
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        formatter = new SimpleDateFormat("yyyy年MM月dd日");
        String time = PreferenceHelper.readString(this, "reminder", "time");
        String str = formatter.format(new Date(System.currentTimeMillis()));
        mainPresenter = new MainPresenter(this);
        initChildeView();
        mainPresenter.requestUpdate(SystemUtils.getAppVersionName(this), YMUserManager.getUserId(this));
        initData();
        //if (!TextUtils.isEmpty(time)) {
        //    if (!time.equals(str)) {
//        requestInitData();
        //    }
        //} else {
        //    requestInitData();
        //}
        PermissionsChecker.getInstance().RequesetPermission(this);
        sContext = this;
    }

//    private void requestInitData() {
//        if (mainPresenter != null) {
//            if (!TextUtils.isEmpty(YMUserManager.getUserId(this))) {
//                //mainPresenter.requestReminder(YMUserManager.getUserId(this));
//                //Date curDate = new Date(System.currentTimeMillis());//获取当前时间
//                //String time = formatter.format(curDate);
//                //PreferenceHelper.write(this, "reminder", "time", time);
//                //AlarmService.dailyNotification(this);
//                Intent intent = new Intent(MainActivity.this, AlarmService.class);
//                intent.putExtra("user_id", YMUserManager.getUserId(this));
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startService(intent);
//            }
//        }
//    }

    /**
     * 请求一些只需要请求一次
     * app初始化的数据
     */

    private void initData() {
        mFragments = new ArrayList<>();
        IndexFragment indexFragment = new IndexFragment();
        mFragments.add(POSITION_INDEX, indexFragment);
        mPageChangeLisenters.add((IPageChangedListener) mFragments.get(POSITION_INDEX));

        //OrderFragment orderFragment = new OrderFragment();
        InterlocutionFragment interlocutionFragment = new InterlocutionFragment();
        mFragments.add(POSITION_INTERLOCUTION, interlocutionFragment);
        mPageChangeLisenters.add((IPageChangedListener) mFragments.get(POSITION_INTERLOCUTION));

        DynamicFragment feedbackFragment = new DynamicFragment();
        mFragments.add(POSITON_FEEDBACK, feedbackFragment);
        mPageChangeLisenters.add((IPageChangedListener) mFragments.get(POSITON_FEEDBACK));

        PersonalFragment personalFragment = new PersonalFragment();
        mFragments.add(POSITION_PERSONAL, personalFragment);
        mPageChangeLisenters.add((IPageChangedListener) mFragments.get(POSITION_PERSONAL));


        tabTitles = Arrays.asList("首页", "问答", "动态", "我的");
        tabView.setTextColor(Color.parseColor("#999999"), Color.parseColor("#0db09b"));
        tabImagesNor = Arrays.asList(R.mipmap.tab_index_nor, R.mipmap.tab_interlocution_nor, R.mipmap.tab_feedback_nor, R.mipmap.tab_person_nor);
        tabImagesSel = Arrays.asList(R.mipmap.tab_index_sel, R.mipmap.tab_interlocution_sel, R.mipmap.tab_feedback_sel, R.mipmap.tab_person_sel);
        tabView.setTabItemTitles(tabTitles);
        tabView.setmTabImage(tabImagesNor);
        tabView.setmHightTabImage(tabImagesSel);
        tabView.setOnPageChangeListener(this);
        TabPageAdapter pageAdapter = new TabPageAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(pageAdapter);
        tabView.setViewPager(mViewPager, mCurrentView);
        onPageSelected(mCurrentView);
        mViewPager.setOffscreenPageLimit(4);
        personalCenter = tabView.getChildAt(2);
        pipuwindow();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !ishow) {
            ishow = true;
            if (!TextUtils.isEmpty(isShowGuide) && isShowGuide.equals("yes")) {

            if (StatusBarCompat.hasNavBar(this)){
                int height= StatusBarCompat.getNavigationBarHeight(this);
                if (Build.VERSION.SDK_INT>=26){
                    pomenuGuid.showAsDropDown(tvBg, 0, DensityUtils.px2dip(this,-height)+35);
                }else{
                    pomenuGuid.showAsDropDown(tvBg, 0, DensityUtils.px2dip(this,-height)-20);
                }
            }else{
                pomenuGuid.showAsDropDown(tvBg, 0, 0);
            }

            }
        }
    }

    private void initChildeView() {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            int pos = bundle.getInt("pos", -1);
            if (pos > -1 && pos < 4) {
                setCurrentView(pos);
            }
            int childView = bundle.getInt("childView", -1);
//            if (childView > -1 && childView < 2) {
//                ClassifyFragment.setCurrentClassifyView(childView);
//            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPageChangeLisenters != null) {
            mPageChangeLisenters.clear();
        }
        if (mFragments != null) {
            mFragments.clear();
        }
        if (pomenuGuid.isShowing()) {
            pomenuGuid.dismiss();
        }

    }

    @Override
    public void onBackPressed() {
        long spent = System.currentTimeMillis() - mInterval;
        if (spent < mDiffTime
                && ShiliaoApplication.getInstance() != null) {
            ShiliaoApplication.getInstance().exit();
        } else {
            showToast(getString(R.string.app_exit_tip));
            //Toast.makeText(this, R.string.app_exit_tip, Toast.LENGTH_SHORT).show();
            mInterval = System.currentTimeMillis();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // LogUtil.e("yjl", "mainactivity onNewIntent");
        // initChildeView();
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            int pos = bundle.getInt("pos", -1);
            if (pos > -1 && pos < 4) {
                if (pos == mCurrentView) {
                    onPageSelected(mCurrentView);
                } else {
                    setCurrentView(pos);
                }
                int childView = bundle.getInt("childView", -1);
//                if (childView > -1 && childView < 2) {
//                    ClassifyFragment.setCurrentClassifyView(childView);
//                }
            }
            // mViewPager.setCurrentItem(mCurrentView);
            tabView.setViewPager(mViewPager, mCurrentView);
        }
    }

    @Override
    public void onEventMainThread(BaseMessageEvent event) {
        if (event instanceof MessageEvent) {
            MessageEvent MEvent = (MessageEvent) event;
            if (event.eventId == MessageEvent.EVENT_ID_NEW_MSG_STATUS_CHANGE) {
                // showToast("new message status changed!");
                if (!bShowNewMsg && YMUserManager.bHasnewmessage) {
                    tabImagesNor = Arrays.asList(R.mipmap.tab_index_nor, R.mipmap.tab_interlocution_nor, R.mipmap.tab_feedback_nor, R.mipmap.tab_person_nor_1);
                    tabView.setmTabImage(tabImagesNor);
                    mViewPager.invalidate();
                    bShowNewMsg = true;
                }
                if (bShowNewMsg && (!YMUserManager.bHasnewmessage)) {
                    tabImagesNor = Arrays.asList(R.mipmap.tab_index_nor, R.mipmap.tab_interlocution_nor, R.mipmap.tab_feedback_nor, R.mipmap.tab_person_nor);
                    tabView.setmTabImage(tabImagesNor);
                    mViewPager.invalidate();
                    bShowNewMsg = false;
                }
            }
        }

    }

    @Override
    public void onEventBackgroundThread(BaseMessageEvent event) {
        super.onEventBackgroundThread(event);
        if (event instanceof MessageEvent) {
//            Log.e("yjl", "mainActivity onEventBackgroundThread event id" + event.eventId + "==========eventName:" + event.eventName);
        }
    }

    @Override
    public void onPageSelected(int position) {
        LogUtil.e("yjl", "mainactivity onPageSelected:" + position);
        setCurrentView(position);
        if (mPageChangeLisenters != null && mPageChangeLisenters.size() > 0) {
            for (int i = 0; i < mPageChangeLisenters.size(); i++) {
                IPageChangedListener pageListener = mPageChangeLisenters.get(i);
                pageListener.onPageChanged(position);
            }
        }
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class TabPageAdapter extends FragmentPagerAdapter {

        public TabPageAdapter(FragmentManager fm) {
            super(fm);
//            LogUtil.e("yjl", "fragment size:" + mFragments.size());
        }

        @Override
        public CharSequence getPageTitle(int position) {

            if (mFragments != null && mFragments.size() > 0 && position < mFragments.size()) {
                return mFragments.get(position).getClass().getSimpleName();
            }
            return "";
        }

        @Override
        public int getCount() {
            if (mFragments != null) {
                return mFragments.size();
            }
            return 0;
        }

        @Override
        public Fragment getItem(int position) {
            return (mFragments != null || (mFragments.size() > 0 && position < mFragments.size())) ?
                    mFragments.get(position) : null;
        }
    }


    @Override
    public void showDownloadDialog(final UpdateEntity updateEntity) {
        LogUtil.e("yzq", "vesion:" + updateEntity.getVesion() + "=====" + Float.valueOf(SystemUtils.getAppVersionName(this)));
        if (updateEntity != null
                && updateEntity.getStatus() == 200
                && updateEntity.getVesion() > Float.valueOf(SystemUtils.getAppVersionName(this))
                &&updateEntity.forceUpdate==1) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (yimeiFileDownloadDialog == null) {
                        yimeiFileDownloadDialog = new YimeiFileDownloadDialog(MainActivity.this, updateEntity);
                    } else {
                        yimeiFileDownloadDialog.setUpdateEntity(updateEntity);
                    }
                    if (!yimeiFileDownloadDialog.isShowing()) {
                        yimeiFileDownloadDialog.show(false);
                    }
                }
            });
        }
    }

    @Override
    public void sendNotice(String isNotice, String noticeTitle) {
//        String time = PreferenceHelper.readString(this, "reminder", "time");
//        String str = formatter.format(new Date(System.currentTimeMillis()));
//        LogUtil.e("yzq", str + "...." + time);
        if (!TextUtils.isEmpty(isNotice) && isNotice.equals("yes")) {
            notice(noticeTitle);
        }
    }

    public void notice(String conten) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Intent intent = new Intent(this, MainActivity.class);  //需要跳转指定的页面
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.mipmap.ic_launcher);// 设置图标
        builder.setContentTitle("日常提醒");// 设置通知的标题
        builder.setContentText(conten);// 设置通知的内容
        builder.setWhen(System.currentTimeMillis());// 设置通知来到的时间
        builder.setAutoCancel(true); //自己维护通知的消失
        builder.setTicker("消息提醒");// 第一次提示消失的时候显示在通知栏上的
        builder.setPriority(Notification.PRIORITY_DEFAULT); //设置该通知优先级
        builder.setOngoing(true);
        builder.setNumber(1);
        //  builder.setDefaults(Notification.DEFAULT_ALL);
        builder.setVibrate(new long[]{0, 300, 500, 700});
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_NO_CLEAR;  //只有全部清除时，Notification才会清除
        notificationManager.notify(0, notification);
//        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
//        String time = formatter.format(curDate);
//        PreferenceHelper.write(this,"reminder","time",time);
//        LogUtil.e("yzq",time);
    }


    private void pipuwindow() {
        isShowGuide = PreferenceHelper.readString(this, FileNameManage.WELCOME_PAGE,
                FileNameManage.WELCOME_PAGE_INFOSETTING_GUID);//存储分享指导);

        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_index_guide, null, false);
        pomenuGuid = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        pomenuGuid.setBackgroundDrawable(new BitmapDrawable());
        pomenuGuid.setFocusable(true);
        pomenuGuid.setOutsideTouchable(true);
        TextView infosettingGuide = contentView.findViewById(R.id.iv_infosetting_guide);
        ImageView infosettingGuide1 = contentView.findViewById(R.id.iv_infosetting_guide1);
        if (!TextUtils.isEmpty(isShowGuide) && isShowGuide.equals("yes")) {//infosettingGuide 为yes才显示引导
            infosettingGuide.setVisibility(View.VISIBLE);
            infosettingGuide1.setVisibility(View.VISIBLE);
        } else {
            infosettingGuide.setVisibility(View.GONE);
            infosettingGuide1.setVisibility(View.GONE);
        }

        contentView.findViewById(R.id.popwin_supplier_list_bottom).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pomenuGuid.dismiss();
            }
        });


    }

}
